package com.dsjy.yf.address.security.service;

import com.dsjy.yf.address.security.common.api.CommonResult;
import com.dsjy.yf.address.security.utils.CommonResultUtil;
import com.dsjy.yf.address.security.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;



import java.util.HashMap;

/**
 * @author whj
 * @version 1.0
 * @date 2021-03-05 16:57
 */
@Service
public class JwtAuthService {
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Qualifier("users")
    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    AuthenticationManager authenticationManager;

    public CommonResult<HashMap<String, String>> login(String username, String password) {
        UsernamePasswordAuthenticationToken token
                = new UsernamePasswordAuthenticationToken(username, password);
        Authentication authenticate = authenticationManager.authenticate(token);
        SecurityContextHolder.getContext().setAuthentication(authenticate);
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        String t = jwtTokenUtil.generateToken(userDetails);
        HashMap<String, String> dataMap = new HashMap<>(2);
        dataMap.put("token", t);
        dataMap.put("roles", userDetails.getAuthorities().toString());
        return CommonResultUtil.success(dataMap);
    }
}
